package com.example.springbootstudy03jsp.controller;

import com.example.springbootstudy03jsp.bean.User;
import com.example.springbootstudy03jsp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/User")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/find")
    public ModelAndView find(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("list",userService.findAll());
        modelAndView.setViewName("index");
        return modelAndView;
    }
    @GetMapping("/find/{id}")
    public ModelAndView findAll(@PathVariable("id") Integer id){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("list",userService.findById(id));
        modelAndView.setViewName("index");
        return modelAndView;
    }
    @GetMapping("save")
    public ModelAndView saveFrom(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("save");
        return modelAndView;
    }
    @PostMapping("/save")
    public String save(User user){
        userService.save(user);
        return "redirect:/User/find";
    }
    @GetMapping("/update/{id}")
    public ModelAndView updateFrom(@PathVariable("id") Integer id){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("user",userService.findById(id));
        modelAndView.setViewName("update");
        return modelAndView;
    }
    @PostMapping("/update")
    public String update(User user){
        System.out.println(user);
        userService.update(user);
        return "redirect:/User/find";
    }
    @GetMapping("/delect/{id}")
    public String delect(@PathVariable("id") Integer id){
        userService.delect(id);
        return "redirect:/User/find";
    }
}
